package mylab.base.foundation.orm.ability;

import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

import cn.hutool.db.Entity;
import cn.hutool.db.Page;
import cn.hutool.db.PageResult;
import cn.hutool.db.handler.BeanHandler;
import cn.hutool.db.handler.BeanListHandler;
import cn.hutool.db.handler.RsHandler;
import cn.hutool.db.sql.Condition;
import mylab.base.foundation.lang.Identifiable;
import mylab.base.foundation.orm.EntityUtil;

public interface Select<T extends Identifiable<Long>> extends DS, EntityInfo<T> {

    default long count() throws SQLException{
        Entity where = EntityUtil.where(getTableName());
        return getDb().count(where);
    }

    default long selectCount(Entity where) throws SQLException{
        return getDb().count(where);
    }

    default T selectById(Long id) throws SQLException{
        Entity where = EntityUtil.where(getTableName());
        where.set("id", id);
        RsHandler<T> rsHandler = BeanHandler.create(getEntityClass());
        return getDb().find(where, rsHandler);
    }

    default List<T> selectAll() throws SQLException {
        Entity where = EntityUtil.where(getTableName());
        return selectList(where);
    }

    default List<T> selectList(Collection<Long> ids) throws SQLException{
        Entity where = EntityUtil.where(getTableName());
        where.addCondition(new Condition("id", "in", ids));
        return selectList(where);
    }

    default List<T> selectList(Entity where) throws SQLException{
        BeanListHandler<T> rsHandler = BeanListHandler.create(getEntityClass());
        return getDb().find(where, rsHandler);
    }

   default PageResult<T> selectPage(Page page, Entity where) throws SQLException{
       PageResult<Entity> pageResult = getDb().page(where, page);
       return EntityUtil.toBean(pageResult, getEntityClass());
   }
}
